package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-res-man/chone"
	"red-res-man/modler"
	"strconv"
	"time"
)

func UserList(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")

	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	book := modler.Book{

		Title:   title,
		Content: content,
		Author:  author,
	}
	err := modler.DB.Create(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "UserList" + strconv.Itoa(int(book.ID))
	var list modler.Book
	modler.DB.Where("id=?", book.ID).First(&list)
	marshal, _ := json.Marshal(&list)
	chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	id := c.Query("id")
	var book []modler.Book
	err := modler.DB.Where("id=?", id).First(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": book,
		})
		return
	}
}

func Del(c *gin.Context) {
	id := c.Query("id")
	err := modler.DB.Where("id=?", id).Delete(&modler.Book{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	redis_key := "del" + id
	chone.Rdb.Get(chone.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func ListAdc(c *gin.Context) {
	var book []modler.Book

	redis_key := "ListAdc"
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Find(&book)
		marshal, _ := json.Marshal(&book)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)

	} else {
		json.Unmarshal([]byte(result), &book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": book,
	})
	return
}
